package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 根据id查询子节点数据
     *
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator") //key
    public List<Dict> findChildData(Long id) {
        //查出id下的所有子节点数据
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        //向list的每个数据设置hasChildren
        dicts.stream().forEach(item -> item.setHasChildren(isChilren(item.getId())));

        return dicts;
    }

    /**
     * 导出数据
     *
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        //查询数据库
        List<Dict> dicts = baseMapper.selectList(null);
        //dict-->dictVo
        List<DictEeVo> list = dicts.stream().map(item -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(item, dictEeVo);
            return dictEeVo;
        }).collect(Collectors.toList());

        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据
     *
     * @param file
     */

    @Override
    @CacheEvict(value = "dict", allEntries = true)//情况缓存
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据dictCode和value查询dictName
     *
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isBlank(dictCode)) {
            return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value)).getName();
        }
        Long id = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode)).getId();
        return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id).eq(Dict::getValue, value)).getName();
    }

    /**
     * 根据dictcode获取下级节点
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应id
        Dict dictByDictCode = this.getDictByDictCode(dictCode);
        //根据id获取子节点
        return this.findChildData(dictByDictCode.getId());
    }

    /**
     * 根据dictCode获取dict
     */
    private Dict getDictByDictCode(String dictCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
    }

    /**
     * 判断id数据下面是否有子节点
     */
    private Boolean isChilren(Long id) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id)) > 0;
    }
}
